﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SpaceShip001
{
    class Terrain
    {
        private int width;
        private int height;
        private VertexPositionTexture[] vertices;
        private int[] indices;
        private Texture2D terrainTextur;
        private GraphicsDevice device;
        BasicEffect effect;
        Camera camera;

        public Terrain(int terrainWidth, int terrainHeight, Texture2D terrainTextur, GraphicsDevice device, Camera camera)
        {
            width = terrainWidth;
            height = terrainHeight;
            this.terrainTextur = terrainTextur;
            this.device = device;
            this.camera = camera;
            effect = new BasicEffect(device);

            SetupVertices();
            SetupIndices();
        }

        private void SetupVertices()
        {
            vertices = new VertexPositionTexture[width * height];

            for (int x = 0; x < width; x++)
            {
                for (int z = 0; z < height; z++)
                {
                    vertices[x + (z * width)].Position = new Vector3(x, 0, -z);
                    vertices[x + (z * width)].TextureCoordinate.X = -x / (float)width;
                    vertices[x + (z * width)].TextureCoordinate.Y = -z / (float)height;

                }
            }
        }

        private void SetupIndices()
        {
            indices = new int[(width - 1) * (height - 1) * 2 * 3];
            int index = 0;
            for (int x = 0; x < width - 1; x++)
                for (int z = 0; z < height - 1; z++)
                {
                    int downLeft = x + (z * width);
                    int upLeft = x + ((z + 1) * width);
                    int upRight = (x + 1 ) + ((z + 1) * width);
                    int downRight = (x + 1) + (z * width);

                    indices[index++] = downLeft;
                    indices[index++] = upLeft;
                    indices[index++] = downRight;

                    indices[index++] = downRight;
                    indices[index++] = upLeft;
                    indices[index++] = upRight;
                }
        }

        public void DrawTerrain(Camera camera)
        {
            effect.World = Matrix.Identity;
            effect.View = camera.view;
            effect.Projection = camera.projection;
            effect.Texture = terrainTextur;
            effect.TextureEnabled = true;
            effect.CurrentTechnique.Passes[0].Apply();

            device.DrawUserIndexedPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3);
        }

    }
}
